#!/bin/sh

## Variables
_if0=eth0
_if1=$1
_br0=kvm-br0
#_hwaddr='00:01:2e:bb:28:62'
#_ipaddr='192.168.1.5'
#_bcast='192.168.1.255'
#_netmask='255.255.255.0'
#_gateway='192.168.1.1'

## Dynamic variables
_hwaddr=$(ip link show dev $_if0 | grep link | awk '{print $2}')
_ipaddr=$(ip addr show dev $_if0 | egrep -o 'inet ([0-9]{,3}.){3}.[0-9]{,3}' | awk '{print $2}')
_bcast=$(ip addr show dev $_if0 | grep inet | egrep -o 'brd ([0-9]{,3}.){3}.[0-9]{,3}' | awk '{print $2}')

## Tools
_IP="/sbin/ip"
_DHCLIENT="/sbin/dhclient"
_IFCONFIG="/sbin/ifconfig"
_TUNCTL="/usr/sbin/tunctl"
_BRCTL="/sbin/brctl"
_ID="/usr/bin/id"

echo "2.0] Executing /etc/qemu-ifup:"
## If there are any available tun/tap interfaces we assume that one
## or more VM instances are already running. Therefore all we do,
## it is add new tun/tap interface to an existent bridge.
echo "Searching for TUN/TAP interfaces..."
if $_IP link show | grep -q 'tap'; then
	echo "Found one or more TAP interface."
	echo -e "\n2.1] Creating additional $_if1 and bringing it up to promisc mode"
	$_TUNCTL -u $($_ID -un) -t $_if1 && sleep 1
	echo 1/3
	$_IFCONFIG $_if1 0.0.0.0 promisc up && sleep 1
	echo 2/3
	echo -e "\n2.2] Adding $_if1 to $_br0..."
	$_BRCTL addif $_br0 $_if1 && sleep 1
	echo 3/3

else
## Otherwise (first VM is just about to be initiated) there is
## a lot more work to do.
	echo "No TAP interface found."

	echo -e "\n2.1] Setting up $_if0 to promisc mode"
	$_IFCONFIG $_if0 down &> /dev/null
	echo 01/10
	$_IFCONFIG $_if0 0.0.0.0 promisc up && sleep 1
	echo 02/10

	echo -e "\n2.2] Creating $_if1 and bringing up to promisc mode"
	$_TUNCTL -u $($_ID -un) -t $_if1 && sleep 1
	echo 03/10
	$_IFCONFIG $_if1 0.0.0.0 promisc up && sleep 1
	echo 04/10

	echo -e "\n2.3] Creating $_br0, including $_if0 and $_if1 to $_br0..."
	$_BRCTL addbr $_br0 && sleep 1
	echo 05/10
	$_BRCTL addif $_br0 $_if0 $_if1 && sleep 1
	echo 06/10

	echo -e "\n2.4] Setting up interfaces..."
	$_BRCTL stp $_br0 off && sleep 1
	echo 07/10
	$_IFCONFIG $_br0 hw ether $_hwaddr && sleep 1
	echo 08/10
	#$_IFCONFIG $_br0 $_ipaddr broadcast $_bcast netmask $_netmask up
	$_IFCONFIG $_br0 up && sleep 2
	echo 09/10
	$_DHCLIENT $_br0 && sleep 1
	echo 10/10
fi
